package com.tjetc.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogUtil {
    private static final String LOG_DIR = "logs";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static {
        // 确保日志目录存在
        File dir = new File(LOG_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    public static void info(String message) {
        log("INFO", message);
    }

    public static void error(String message, Throwable e) {
        log("ERROR", message);
        if (e != null) {
            log("ERROR", "异常详情: " + e.getMessage());
            for (StackTraceElement element : e.getStackTrace()) {
                log("ERROR", element.toString());
            }
        }
    }

    public static void warn(String message) {
        log("WARN", message);
    }

    public static void debug(String message) {
        log("DEBUG", message);
    }

    private static synchronized void log(String level, String message) {
        String today = DATE_FORMAT.format(new Date());
        String logFile = LOG_DIR + File.separator + "community_" + today + ".log";
        
        try (PrintWriter writer = new PrintWriter(new FileWriter(logFile, true))) {
            String logMessage = String.format("[%s] [%s] %s",
                    TIME_FORMAT.format(new Date()),
                    level,
                    message);
            writer.println(logMessage);
            // 同时输出到控制台
            System.out.println(logMessage);
        } catch (IOException e) {
            System.err.println("写入日志文件失败: " + e.getMessage());
        }
    }
} 